<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <el-card>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item label="成品料号 ">
          <el-input
            v-model="queryParams.contractNo"
            placeholder="请输入成品料号 "
            clearable
            @keydown.enter.native.prevent="handleQuery"
          />
        </el-form-item>
        <el-form-item label="报关单号">
          <el-select
            v-model="queryParams.customsNo"
            placeholder="请选择报关单号"
            filterable
            clearable
          >
            <el-option
              v-for="item in customsOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="原料号">
          <el-input
            v-model="queryParams.materialNo"
            placeholder="请输入原料号"
            clearable
            @keydown.enter.native.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item label="工单号">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入工单号"
            clearable
            @keydown.enter.native.prevent="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格与新增按钮 -->
    <el-card class="mt20">
      <el-row justify="space-between" class="mb10">
        <span style="font-size: 18px">工单记录</span>
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增记录</el-button
        >
      </el-row>
      <el-table :data="recordList" border stripe v-loading="loading">
        <el-table-column prop="orderNo" label="工单号" />
        <el-table-column prop="customsNo" label="报关单号" />
        <el-table-column prop="contractNo" label="成品料号" />
        <el-table-column prop="productName" label="成品品名" />
        <el-table-column prop="theoreticalOutput" label="成品理论产出" />
        <el-table-column prop="actualOutput" label="成品实际产出" />
        <el-table-column prop="materialNo" label="原料号" />
        <el-table-column prop="materialName" label="原料品名" />
        <el-table-column prop="theoreticalConsumption" label="原料理论耗用" />
        <el-table-column prop="actualConsumption" label="原料实际耗用" />
        <el-table-column prop="voucherTime" label="凭证时间" />
        <el-table-column prop="orderCreator" label="经办人" />
        <el-table-column prop="orderTime" label="开单时间" />
        <el-table-column prop="processTime" label="加工时间" />
        <el-table-column prop="finishTime" label="完结时间" />
        <el-table-column prop="singleWeight" label="单包重量（KG）" />
        <el-table-column prop="totalWeight" label="总重量（吨）" />
        <el-table-column prop="usedPackage" label="包装用量（条）" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetail(row)"
              >编辑</el-button
            >
            <el-button
              v-hasPermi="['work:all:delete']"
              link
              type="danger"
              @click="deleteRow(row)"
              >删除</el-button
            >
            <el-button link @click="showDetails(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 新增/编辑 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id ? '编辑记录' : '新增记录'"
      width="600px"
    >
      <el-form :model="formData" ref="formRef" label-width="120px">
        <el-form-item label="工单号" prop="orderNo">
          <el-input v-model="formData.orderNo" />
        </el-form-item>
        <el-form-item label="报关单号" prop="报关单号">
          <el-select
            v-model="formData.customsNo"
            placeholder="请选择报关单号"
            filterable
            clearable
          >
            <el-option
              v-for="item in customsOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成品料号" prop="contractNo">
          <el-input v-model="formData.contractNo" />
        </el-form-item>
        <el-form-item label="成品品名" prop="productName">
          <el-input v-model="formData.productName" />
        </el-form-item>
        <el-form-item label="成品理论产出" prop="theoreticalOutput">
          <el-input-number v-model="formData.theoreticalOutput" :min="0" />
        </el-form-item>
        <el-form-item label="成品实际产出" prop="actualOutput">
          <el-input-number v-model="formData.actualOutput" :min="0" />
        </el-form-item>
        <el-form-item label="原料号" prop="materialNo">
          <el-input v-model="formData.materialNo" />
        </el-form-item>
        <el-form-item label="原料品名" prop="materialName">
          <el-input v-model="formData.materialName" />
        </el-form-item>
        <el-form-item label="原料理论耗用" prop="theoreticalConsumption">
          <el-input-number v-model="formData.theoreticalConsumption" :min="0" />
        </el-form-item>
        <el-form-item label="原料实际耗用" prop="actualConsumption">
          <el-input-number v-model="formData.actualConsumption" :min="0" />
        </el-form-item>
        <el-form-item label="凭证时间" prop="voucherTime">
          <el-date-picker
            v-model="formData.voucherTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="经办人" prop="orderCreator">
          <el-input v-model="formData.orderCreator" />
        </el-form-item>
        <el-form-item label="开单时间" prop="orderTime">
          <el-date-picker
            v-model="formData.orderTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="加工时间" prop="processTime">
          <el-date-picker
            v-model="formData.processTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="完结时间" prop="finishTime">
          <el-date-picker
            v-model="formData.finishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="单包重量（KG）" prop="singleWeight">
          <el-input-number v-model="formData.singleWeight" :min="0" />
        </el-form-item>
        <el-form-item label="总重量（吨）" prop="totalWeight">
          <el-input-number
            v-model="formData.totalWeight"
            :min="0"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="包装用量（条）" prop="usedPackage">
          <el-input-number v-model="formData.usedPackage" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="工单详情" v-model="detailVisible" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单号">{{
          detailData.orderNo
        }}</el-descriptions-item>
        <el-descriptions-item label="成品料号">{{
          detailData.contractNo
        }}</el-descriptions-item>
        <el-descriptions-item label="成品品名">{{
          detailData.productName
        }}</el-descriptions-item>
        <el-descriptions-item label="成品理论产出">{{
          detailData.theoreticalOutput
        }}</el-descriptions-item>
        <el-descriptions-item label="成品实际产出">{{
          detailData.actualOutput
        }}</el-descriptions-item>
        <el-descriptions-item label="原料号">{{
          detailData.materialNo
        }}</el-descriptions-item>
        <el-descriptions-item label="原料品名">{{
          detailData.materialName
        }}</el-descriptions-item>
        <el-descriptions-item label="原料理论耗用">{{
          detailData.theoreticalConsumption
        }}</el-descriptions-item>
        <el-descriptions-item label="原料实际耗用">{{
          detailData.actualConsumption
        }}</el-descriptions-item>
        <el-descriptions-item label="凭证时间">{{
          detailData.voucherTime
        }}</el-descriptions-item>
        <el-descriptions-item label="经办人">{{
          detailData.orderCreator
        }}</el-descriptions-item>
        <el-descriptions-item label="开单时间">{{
          detailData.orderTime
        }}</el-descriptions-item>
        <el-descriptions-item label="加工时间">{{
          detailData.processTime
        }}</el-descriptions-item>
        <el-descriptions-item label="完结时间">{{
          detailData.finishTime
        }}</el-descriptions-item>
        <el-descriptions-item label="单包重量（KG）">{{
          detailData.singleWeight
        }}</el-descriptions-item>
        <el-descriptions-item label="总重量（吨）">{{
          detailData.totalWeight
        }}</el-descriptions-item>
        <el-descriptions-item label="包装用量（条）">{{
          detailData.usedPackage
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  workorder_list as listProduce,
  workorder_add as addProduce,
  workorder_edit as updateProduce,
  workorder_delete as delProduce,
  details as getDetails,
} from "@/api/wms/workorder";
import { queryCustomsNoList, queryMaterialNoList } from "@/api/wms/whole";

const loading = ref(false);
const total = ref(0);
const dialogVisible = ref(false);
const detailVisible = ref(false);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  contractNo: "", // 成品料号
  materialNo: "", // 原料号
  customsNo: "", // 报关单号
  orderNo: "", // 工单号
  finishStartTime: "",
  finishEndTime: ""
});
// 日期范围
const dateRange = ref([]); // [start, end]

const recordList = ref([]);
const customsOptions = ref([]);
const liaohaoOptions = ref([]);

const formData = reactive({
  id: null,
  singleWeight: 0, // 单包重量（KG）
  totalWeight: 0, // 总重量（吨）
  orderCreator: "", // 经办人
  orderNo: "", // 工单号
  contractNo: "", // 成品料号
  customsNo: "", // 报关单号
  usedPackage: "", // 包装用量（条）"
});

const detailData = reactive({
  singleWeight: 0, // 单包重量（KG）
  totalWeight: 0, // 总重量（吨）
  orderCreator: "", // 经办人
  orderNo: "", // 工单号
  contractNo: "", // 成品料号
  customsNo: "", // 报关单号
  usedPackage: "", // 包装用量（条）"
  productName: "", // 成品品名
  theoreticalOutput: null, // 成品理论产出
  actualOutput: null, // 成品实际产出
  materialNo: "", // 原料号
  materialName: "", // 原料品名
  theoreticalConsumption: null, // 原料理论耗用
  actualConsumption: null, // 原料实际耗用
  voucherTime: "", // 凭证时间（建议用 ISO 字符串）
  orderTime: "", // 开单时间
  processTime: "", // 加工时间
  finishTime: "", // 完结时间
  customsNo: ""
});

function resetForm() {
  Object.assign(formData, {
    id: null,
    singleWeight: 0, // 单包重量（KG）
    totalWeight: 0, // 总重量（吨）
    orderCreator: "", // 经办人
    orderNo: "", // 工单号
    contractNo: "", // 成品料号
    customsNo: "", // 报关单号
    usedPackage: "", // 包装用量（条）"
    productName: "", // 成品品名
    theoreticalOutput: null, // 成品理论产出
    actualOutput: null, // 成品实际产出
    materialNo: "", // 原料号
    materialName: "", // 原料品名
    theoreticalConsumption: null, // 原料理论耗用
    actualConsumption: null, // 原料实际耗用
    voucherTime: "", // 凭证时间（建议用 ISO 字符串）
    orderTime: "", // 开单时间
    processTime: "", // 加工时间
    finishTime: "", // 完结时间
    customsNo: ""
  });
}

function handleAdd() {
  resetForm();
  dialogVisible.value = true;
}

function viewDetail(row) {
  Object.assign(formData, { ...row });
  dialogVisible.value = true;
}

async function handleQuery() {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.finishStartTime = dateRange.value[0];
    queryParams.finishEndTime = dateRange.value[1];
  } else {
    queryParams.finishStartTime = "";
    queryParams.finishEndTime = "";
  }

  loading.value = true;
  try {
    const res = await listProduce(queryParams);
    res.rows.forEach((pre) => {
      pre.singleWeight = (+pre.singleWeight).toFixed(3);
      pre.totalWeight = (+pre.totalWeight).toFixed(3);
    });
    recordList.value = res.rows || [];
    total.value = res.total || 0;
  } catch {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
}

function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.contractNo = "";
  queryParams.customsNo = "";
  queryParams.materialNo = "";
  queryParams.orderNo = "";
  queryParams.finishStartTime = "";
  queryParams.finishEndTime = "";
  dateRange.value = [];
  handleQuery();
}

async function submitForm() {
  try {
    if (formData.id) {
      await updateProduce(formData);
      ElMessage.success("更新成功");
    } else {
      await addProduce(formData);
      ElMessage.success("新增成功");
    }
    dialogVisible.value = false;
    handleQuery();
  } catch {
    ElMessage.error("提交失败");
  }
}

function deleteRow(row) {
  ElMessageBox.confirm("确定要删除此记录吗？", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await delProduce(row.id);
      ElMessage.success("删除成功");
      handleQuery();
    } catch {
      ElMessage.error("删除失败");
    }
  });
}

async function loadSelectOptions() {
  try {
    const [customsRes, liaohao] = await Promise.all([
      queryCustomsNoList(),
      queryMaterialNoList(),
    ]);
    customsOptions.value = customsRes.data.filter((pre) => pre) || [];
    liaohaoOptions.value = liaohao.data.filter((pre) => pre) || [];
  } catch {
    ElMessage.error("加载下拉选项失败");
  }
}

// 详情方法
function showDetails(row) {
  Object.assign(detailData, {
    ...row,
  });
  detailVisible.value = true;
}
// async function showDetails(row) {
//   try {
//     const res = await getDetails({ orderNo: row.orderNo });
//     Object.assign(detailData, {
//       ...row,
//       incomeTon: res.data?.incomeTon || "",
//       scrapKg: res.data?.scrapKg || "",
//     });
//     detailVisible.value = true;
//   } catch {
//     ElMessage.error("获取详情失败");
//   }
// }

onMounted(() => {
  handleQuery();
  loadSelectOptions();
});
</script>

<style scoped>
.mt20 {
  margin-top: 20px;
}
.mb10 {
  margin-bottom: 10px;
}
.pagination-wrapper {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
